package com.project.petLossSystem.controller.admin;

import com.project.petLossSystem.service.UserService;
import com.project.petLossSystem.util.PageQueryUtil;
import com.project.petLossSystem.util.Result;
import com.project.petLossSystem.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/admin")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public String users() {
        return "/pc/admin/users";
    }

    @GetMapping("/users/list")
    @ResponseBody //这里不指定value，将所有参数存入map
    public Result list(@RequestParam Map<String, Object> params) {
        if (ObjectUtils.isEmpty(params.get("page")) || ObjectUtils.isEmpty(params.get("rows"))) {
            return ResultGenerator.failureResult("参数异常！");
        }
        PageQueryUtil pageQueryUtil = new PageQueryUtil(params);
        // 判断userId是否有效
        if (!ObjectUtils.isEmpty(pageQueryUtil.get("userId"))) {
            Long userId = Long.valueOf((String) pageQueryUtil.get("userId"));
            pageQueryUtil.put("userId", userId);
            // 有id了就不要loginId
            pageQueryUtil.remove("loginId");
        } else if (!ObjectUtils.isEmpty(pageQueryUtil.get("loginId"))) {
            // 如果loginId存在
            String loginId = String.valueOf(pageQueryUtil.get("loginId"));
            pageQueryUtil.put("loginId", loginId);
        }
        return ResultGenerator.successResult(userService.getUsersPage(pageQueryUtil));
    }

    @PutMapping("/users/lock/{isLocked}")
    @ResponseBody
    public Result updateLock(@RequestBody Long[] userIds, @PathVariable("isLocked") Byte isLocked) {
        if (userIds.length < 1 || (isLocked != 0 && isLocked != 1)) {
            return ResultGenerator.failureResult("参数非法！");
        }
        if (userService.updateLock(userIds, isLocked)) {
            return ResultGenerator.successResult();
        } else return ResultGenerator.failureResult("操作失败！");
    }

    @PutMapping("/users/delete/{isDeleted}")
    @ResponseBody
    public Result updateDelete(@RequestBody Long[] userIds, @PathVariable("isDeleted") Byte isDeleted) {
        if (userIds.length < 1 || (isDeleted != 0 && isDeleted != 1)) {
            return ResultGenerator.failureResult("参数非法！");
        }
        if (userService.updateDeleted(userIds, isDeleted)) {
            return ResultGenerator.successResult();
        } else return ResultGenerator.failureResult("操作失败！");
    }
}
